//
//  SingleEnterpriseController.swift
//  YiYaoHui
//
//  Created by 高永效 on 15/12/4.
//  Copyright © 2015年 EgeTart. All rights reserved.
//

import UIKit
import MessageUI
import Alamofire
import SDWebImage

class SingleEnterpriseController: UIViewController {
    
    @IBOutlet weak var enterpriseLogoView: UIImageView!
    @IBOutlet weak var enterpriseNameLabel: UILabel!
    @IBOutlet weak var enterpriseHomePageButton: UIButton!
    @IBOutlet weak var optionsTableView: UITableView!
    @IBOutlet weak var titleItem: UINavigationItem!
    
    var enterprise: Enterprise! //需要用这个enterprise拿到本企业的id，再请求详细信息
    var isExpand = false
    
    var enterpriseLogo: UIImage!
    
    var enterpriseName = ""
    var enterpriseID = ""
    var homePageURL = ""
    var enterpriseEmail = ""
    var enterprisePhone = ""
    var logoURL: String!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //企业名字
        enterpriseNameLabel.text = enterprise.name
        titleItem.title = enterprise.name
        
        optionsTableView.tableFooterView = UIView(frame: CGRectZero)
        enterpriseHomePageButton.layer.cornerRadius = 7
        enterpriseHomePageButton.clipsToBounds = true
        
        enterpriseLogoView.layer.borderColor = UIColor(red: 153.0 / 255.0, green: 153.0 / 255.0, blue: 153 / 255.0, alpha: 1).CGColor
        enterpriseLogoView.layer.borderWidth = 0.5
        
        navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: UIBarButtonItemStyle.Plain, target: nil, action: nil)
        
        getEnterpriseDetail()
    }
    
    //跳到企业主页   
    @IBAction func viewEnterpriseHomePage(sender: UIButton) {
        getEnterpriseDetail()
        let enterpriseHomePageController  = self.storyboard?.instantiateViewControllerWithIdentifier("concreteMeetingController") as! MeetingDetailController
        enterpriseHomePageController.id = 3
        enterpriseHomePageController.enterpriseHomePageURL = homePageURL
        enterpriseHomePageController.enterpriseTitle = enterprise.name
        self.navigationController?.pushViewController(enterpriseHomePageController, animated: true)
    }
    
    override func viewWillAppear(animated: Bool) {
        tabBarController?.tabBar.hidden = true
        navigationController?.navigationBarHidden = false
    }
    
    //请求企业的详细信息
    func getEnterpriseDetail() {
        let baseURL = "http://112.74.131.194:8080/MedicineProject/App/user/getEnterContent"
        print("请求用的企业id",enterprise.id)
        Alamofire.request(.POST, baseURL, parameters: ["id": enterprise.id], encoding: ParameterEncoding.URL, headers: nil).responseJSON { (_, _, result) -> Void in
            print(result.value) 
            if let value = result.value {
                let state = value["result"] as! String
                if state == "success" {
                    NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in
                        var content = value["enterContent"] as! [String: AnyObject]
                        //这三个绝壁不空
                        self.enterpriseNameLabel.text = content["name"] as? String
                        self.enterpriseID = (content["id"]!.description)
                        self.homePageURL = content["enterpriseUrl"] as! String
                        //后台录入的信息不全， 企业邮件、企业电话、企业logo可能空
                        if content["email"] is NSNull{
                            self.enterpriseEmail = "企业邮箱暂未提供"
                        } else {
                            self.enterpriseEmail = content["email"] as! String
                        }
                        if content["phone"] is NSNull {
                            self.enterprisePhone = "企业电话暂未提供"
                        } else {
                             self.enterprisePhone = content["phone"] as! String
                        }
                        if content["logo"] is NSNull {
                            self.enterpriseLogoView.image = UIImage(named: "logo")
                        } else {
                            self.logoURL = "http://112.74.131.194:8080/MedicineProject" + (content["logo"] as! String)
                            self.enterpriseLogoView.sd_setImageWithURL(NSURL(string: self.logoURL)!, placeholderImage: UIImage(named: "logo"))
                        }
                    })
                }
            }
        }
    }
    
}

extension SingleEnterpriseController: UITableViewDataSource {
    
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 2
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 {
            return 3
        }
        return isExpand == true ? 3 : 1
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        if indexPath.section == 0 {
            let cell = tableView.dequeueReusableCellWithIdentifier("optionCell", forIndexPath: indexPath) as! OptionCell
            switch indexPath.row {
            case 0:
                cell.optionImageView.image = UIImage(named: "medicine_red")
                cell.optionLabel.text = "药品"
                cell.rightImageView.image = UIImage(named: "rightArrow")
                return cell
            case 1:
                cell.optionImageView.image = UIImage(named: "video")
                cell.optionLabel.text = "医药视频"
                cell.rightImageView.image = UIImage(named: "rightArrow")
                return cell
            default:
                cell.optionImageView.image = UIImage(named: "meeting")
                cell.optionLabel.text = "会议视频"
                cell.rightImageView.image = UIImage(named: "rightArrow")
                return cell
            }
        }
        else {
            switch indexPath.row {
            case 0:
                let cell = tableView.dequeueReusableCellWithIdentifier("optionCell", forIndexPath: indexPath) as! OptionCell
                cell.optionImageView.image = UIImage(named: "consult")
                cell.optionLabel.text = "咨询方式"
                if isExpand == true {
                    cell.rightImageView.image = UIImage(named: "upArrow")
                }
                else {
                    cell.rightImageView.image = UIImage(named: "downArrow")
                }
                return cell
            case 1:
                let cell = tableView.dequeueReusableCellWithIdentifier("consultCell", forIndexPath: indexPath)
                let wayLabel = cell.viewWithTag(201) as! UILabel
                wayLabel.text = "热线:"
                let contentLabel = cell.viewWithTag(202) as! UILabel
                contentLabel.text = self.enterprisePhone
                contentLabel.font = UIFont.systemFontOfSize(15)
                contentLabel.textColor = UIColor(red: 85/255, green: 85/255, blue: 85/255, alpha: 1)
                return cell
            default:
                let cell = tableView.dequeueReusableCellWithIdentifier("consultCell", forIndexPath: indexPath)
                let wayLabel = cell.viewWithTag(201) as! UILabel
                wayLabel.text = "邮箱:"
                let contentLabel = cell.viewWithTag(202) as! UILabel
                contentLabel.text = self.enterpriseEmail
                contentLabel.font = UIFont.systemFontOfSize(15)
                 contentLabel.textColor = UIColor(red: 85/255, green: 85/255, blue: 85/255, alpha: 1)
                return cell
            }
        }
    }
    
}

extension SingleEnterpriseController: UITableViewDelegate, MFMailComposeViewControllerDelegate {
    
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        
        switch indexPath.section {
        case 0: //药品、医药视频、会议视频
            switch indexPath.row {
            case 0: //药品
                let enterprisePageMedicineController = self.storyboard?.instantiateViewControllerWithIdentifier("MedicineController") as!MedicinePageController
                //传跳转的值
                enterprisePageMedicineController.id = 2
                enterprisePageMedicineController.enterpriseID = enterpriseID
                
                self.navigationController?.pushViewController(enterprisePageMedicineController, animated: true)
                break
            case 1: //医药视频
                let enterpriseVideoController = self.storyboard?.instantiateViewControllerWithIdentifier("VideoController") as!LastestVideoController
                enterpriseVideoController.id = 2
                enterpriseVideoController.enterpriseID = self.enterpriseID
                self.navigationController?.pushViewController(enterpriseVideoController, animated: true)
                
                break
            default: //会议视频
                // 传值跳转
                let  enterpriseMeetingControlelr = self.storyboard?.instantiateViewControllerWithIdentifier("MeetingController") as! LastestMeetingController
                enterpriseMeetingControlelr.id = 2
                enterpriseMeetingControlelr.enterpriseID = self.enterpriseID
                
                self.navigationController?.pushViewController(enterpriseMeetingControlelr, animated: true)
                
                break
            }
            
            
            break
        case 1:
            switch indexPath.row {
            case 0:
                isExpand = !isExpand
                tableView.reloadSections(NSIndexSet(index: indexPath.section), withRowAnimation: UITableViewRowAnimation.Automatic)
            case 1:
                if let url:NSURL = NSURL(string: "tel://\(self.enterprisePhone)") {
                    UIApplication.sharedApplication().openURL(url)}
            default:
                let mailController = MFMailComposeViewController()
                mailController.mailComposeDelegate = self
                mailController.setToRecipients([enterpriseEmail])
                mailController.setSubject("问题咨询")
                self.presentViewController(mailController, animated: true, completion: nil)
            }
            break
        default:
            break
        }
        tableView.deselectRowAtIndexPath(indexPath, animated: true)
    }
    
    func mailComposeController(controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?) {
        self.dismissViewControllerAnimated(true, completion: nil)
    }
    
    
    func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 8
    }
    
}

